package top.igotcha.chapter.chapter8.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import static java.lang.Thread.sleep;

/**
 * @author Gotcha
 * @date 2021/3/16
 * @describe 自定义不可重入锁
 */
@Slf4j(topic = "AQSTest01")
public class AQSTest01 {
    public static void main(String[] args) {
        Lock lock = new MyLock();
        Thread t1 = new Thread(()->{
            lock.lock();
            try {
                log.debug("t1线程开始");
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });
        Thread t2 = new Thread(()->{
            lock.lock();
            try {
                log.debug("t2线程开始");
            } finally {
                lock.unlock();
            }
        });
        t1.run();
        t2.run();
    }

}

//自定义不可重入锁
class MyLock implements Lock{

    private MySync sync = new MySync();


    //独占锁,同步器类
    class MySync extends AbstractQueuedSynchronizer{
        //尝试获取锁
        @Override
        protected boolean tryAcquire(int arg) {
            if(compareAndSetState(0,1)){
                //加上了锁,设置owner为当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        //是否持有独占锁
        @Override
        protected boolean isHeldExclusively() {
            return getState()==1 ;
        }

        public Condition newCondition(){
            return new ConditionObject();
        }
    }



    //加锁(不成功会进入等待队列)
    @Override
    public void lock() {
        sync.acquire(1);
    }

    //加锁，可打断锁
    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    //尝试加锁，一次
    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    //尝试加锁，带超时
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1,unit.toNanos(time));
    }

    //解锁
    @Override
    public void unlock() {
        sync.release(1);
    }

    //创建条件变量
    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }
}
